package com.kova.api.cipher;

import com.alibaba.fastjson.JSON;
import com.kova.api.common.Result;
import com.kova.api.crypto.Crypto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;
import java.util.Map;

@ControllerAdvice
//@ConditionalOnProperty(prefix = "spring.crypto.response.encrypt", name = "enabled" , havingValue = "true", matchIfMissing = true)
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    //@Value("${spring.crypto.request.decrypt.charset:UTF-8}")
    private String charset = "UTF-8";

    @Autowired
    @Qualifier("rrCrypto")
    private Crypto crypto;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        boolean encrypt = NeedCrypto.needEncrypt(returnType);

        if( !encrypt ){
            return body;
        }

        if(!(body instanceof Result)){
            return body;
        }

        //只针对ResponseMsg的data进行加密
        Result responseMsg = (Result) body;
        Object data = responseMsg.getData();
        if(null == data){
            return body;
        }

        String xx;
        Class<?> dataClass = data.getClass();
        if(dataClass.isPrimitive() || (data instanceof String)){
            xx = String.valueOf(data);
        }else {
            //JavaBean、Map、List等先序列化
            if(List.class.isAssignableFrom(dataClass)){
                //xx = JsonUtil.serializeList((List<Object>) data);
                xx = JSON.toJSONString((List<Object>) data);
            }else if(Map.class.isAssignableFrom(dataClass)){
                //xx = JsonUtil.serializeMap((Map<String, Object>) data);
                xx = JSON.toJSONString((Map<String, Object>) data);
            }else {
                //xx = JsonUtil.serializeJavaBean(data);
                xx = JSON.toJSONString(data);
            }
        }

        responseMsg.setData(crypto.encrypt(xx, charset));

        return responseMsg;
    }

}

